package com.fangcang.baidu;

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

@Component("baiDuApiUtils")
public class BaiDuApiUtils {

	public static final String URL_PREFIX = "http://api.map.baidu.com/geocoder/v2/?";

	public static final String AK = "qynOyqcVpRPNvvLLC5LjX3d9l9YX0u19";

	public static final String SK = "ftIKi3EwiwRzPajgrcvcETxVxZhEipC7";

	@Autowired
	private RestTemplate restTemplate;

	/**
	 * 根据中文地址获取经纬度
	 * 
	 * @param address
	 * @return
	 */
	public BaiduResponseEntity getLocationByAddress(String address) {
		Map<String, String> paramsMap = new LinkedHashMap<String, String>();
		paramsMap.put("address", address);
		paramsMap.put("output", "json");
		paramsMap.put("ak", AK);
		String sn = SnCalculater.getSnString(paramsMap, SK);
		paramsMap.put("sn", sn);

		ResponseEntity<String> result = restTemplate.getForEntity(
				URL_PREFIX + "address={address}&output={output}&ak={ak}&sn={sn}", String.class, paramsMap);
		System.out.println(result.getBody());
		BaiduResponseEntity response = JSONObject.parseObject(result.getBody(), BaiduResponseEntity.class);
		return response;
	}

	/**
	 * 补充：计算两点之间真实距离
	 * 
	 * @return 米
	 */
	public double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
		// 维度
		double lat1 = (Math.PI / 180) * latitude1;
		double lat2 = (Math.PI / 180) * latitude2;

		// 经度
		double lon1 = (Math.PI / 180) * longitude1;
		double lon2 = (Math.PI / 180) * longitude2;

		// 地球半径
		double R = 6371;

		// 两点间距离 km，如果想要米的话，结果*1000就可以了
		double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1))
				* R;

		return d * 1000;
	}

}
